package com.nnfe.fyd.http;

import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * 继承 converter.factory 去解析 response 为 string
 */
public class StringConverterFactory extends retrofit2.Converter.Factory {

    private static final String TAG = "StringConverterFactory";

    public static StringConverterFactory create() {
        return new StringConverterFactory();
    }

    public StringConverterFactory() {
        super();
    }

    @Override
    public Converter<?, String> stringConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        return super.stringConverter(type, annotations, retrofit);
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        // 由于Java没有标准的获取Type方法，借用GSON里的TypeToken来获取
        Type token = new TypeToken<String>() {
        }.getType();
        if (type == token) {
            // 目标类型为String类型则进行转换
            return new StringConverter();
        }
        return super.responseBodyConverter(type, annotations, retrofit);
    }

    private class StringConverter implements Converter {
        @Override
        public Object convert(Object value) throws IOException {
            if (value != null) {
                if (value instanceof ResponseBody) {
                    ResponseBody rb = (ResponseBody) value;
                    return rb.string();
                }
            }
            return null;
        }
    }
}
